<?php

namespace app\admin\controller;

use app\common\model\GiftModel;
use app\common\model\NobleModel;
use app\common\model\NobleNewModel;
use app\common\model\NoblePrivilegeModel;
use app\common\model\NoblePromoModel;
use app\common\model\NobleRecordModel;
use app\common\model\PropsNewModel;
use Exception;
use think\Db;

Class NobleController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $pageIndex = (int)$this->get('page', 1);
            $pageSize = (int)$this->get('limit', 20);

            $model = NobleRecordModel::where('1', '1');
            if (($noble_id = trim($this->get('noble_id', ''))) && is_numeric($noble_id)) {
                $model = $model->where('noble_id', $noble_id);
            }
            if (($id = trim($this->get('id', ''))) && is_numeric($id)) {
                $model = $model->where('uid', $id);
            }

            return json([
                'count' => $model->count(),
                'list' => $model->order('id', 'desc')
                    ->page($pageIndex, $pageSize)
                    ->select()->each(function ($query) {
                        if ($query->user ?? null) {
                            $query->account = $query->user->account;
                        } else {
                            $query->account = '未知账号';
                        }

                        $query->expiration = date('Y-m-d H:i:s', $query->expiration);
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }

        return $this->assign([
            'nobles' => $nobles = NobleModel::lists(),
            'nobles_json' => json_encode(array_column($nobles, 'name', 'id'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)

        ])->fetch();
    }

    public function level()
    {
        if ($this->request->isAjax()) {
            $model = NobleNewModel::where('1', '1');
            $props = array_column(PropsNewModel::listByType(), null, 'id');
            return json([
                'count' => $model->count(),
                'list' => $model->page($this->get('page', 1), $this->get('limit', 20))
                    ->select()->each(function ($query) use($props) {
                        $query->price = $query->price == 0 ? 0 : bcdiv($query->price, '100', 2);
                        $query->renew_price = $query->renew_price == 0 ? 0 : bcdiv($query->renew_price, '100', 2);
                        $query->gift_discount = $query->gift_discount == 0 ? 0 : bcdiv($query->gift_discount, '10', 1);
                        if ($barrage = json_decode($query->barrage, true)) {
                            $query->barrage = $barrage;
                        } else {
                            $query->barrage = null;
                        }

                        if ($trumpet = json_decode($query->trumpet, true)) {
                            $query->trumpet = $trumpet ?? null;
                        } else {
                            $query->trumpet = null;
                        }
                        $query->props_name = $props[$query->props_id]['name'] ?? '';
                    })->toArray(),
                'code' => 0,
            ]);
        }
        return $this->fetch();
    }

    public function level_edit()
    {
        if (!($id = $this->get('id', '')) || !is_numeric($id)) {
            return static::bulidFail('ID错误');
        }

        if (!$model = NobleNewModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的贵族等级');
        }

        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('等级名称不能为空');
            }

            if (mb_strlen($name > 10)) {
                return static::bulidFail('等级名称不能超过十个字符');
            }

            $model->name = $name;
            if (($price = rtrim(trim($this->post('price', '')), '.')) && is_numeric($price)) {
                $model->price = bcmul($price, '100', 0);
            } else {
                $model->price = 0;
            }

            if (($renew_price = rtrim(trim($this->post('renew_price', '')), '.')) && is_numeric($renew_price)) {
                $model->renew_price = bcmul($renew_price, '100', 0);
            } else {
                $model->renew_price = 0;
            }

            if (($gift_discount = rtrim($this->post('gift_discount', ''))) && ctype_digit($gift_discount)) {
                if ($gift_discount > 100) {
                    return static::bulidFail('礼物折扣不能大于100');
                }
                $model->gift_discount = $gift_discount;
            } else {
                $model->gift_discount = 0;
            }

            if (!in_array($props_id = $this->post('props_id', ''), array_column(PropsNewModel::listByType(), 'id'))) {
                return static::bulidFail('你选择的坐骑不存在');
            }

            if (in_array($trumpet_id = $this->post('trumpet_id', ''), array_column($propsArray = array_column(PropsNewModel::listByType(100), null, 'id'), 'id'))) {
                if (ctype_digit($trumpet_num = $this->post('trumpet_num', '')) && $trumpet_num > 0) {
                    $model->trumpet = json_encode(
                        [
                            'name' => $propsArray[$trumpet_id]['name'],
                            'icon' => $propsArray[$trumpet_id]['icon'],
                            'remark' => $propsArray[$trumpet_id]['remark'],
                            'amount' => (int)$trumpet_num,
                            'props_id' => (int)$trumpet_id,
                            'type' => $propsArray[$trumpet_id]['type'],
                        ],
                        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
                    );
                } else {
                    $model->trumpet = '[]';
                }
            } else {
                $model->trumpet = '[]';
            }

            if (is_array($barrage_ids = $this->post('barrage_id', [])) && $barrage_ids) {
                $barrageArray = array_column(PropsNewModel::listByType(101), null, 'id');
                $barrage_num = $this->post('barrage_nums', []);
                $barrages = [];
                foreach ($barrage_ids as $key => $barrage_id) {
                    if (!empty($barrageArray[$barrage_id]) && !empty($barrage_num[$key]) && ctype_digit($barrage_num[$key])) {
                        $barrages[] = [
                            'name' => $barrageArray[$barrage_id]['name'],
                            'icon' => $barrageArray[$barrage_id]['icon'],
                            'remark' => $barrageArray[$barrage_id]['remark'],
                            'amount' => (int)$barrage_num[$key],
                            'props_id' => (int)$barrage_id,
                            'type' => $barrageArray[$barrage_id]['type'],
                        ];
                    }
                }

                $model->barrage = json_encode($barrages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

            } else {
                $model->barrage = '[]';
            }

            $model->props_id = $props_id;
            if (!$model->save()) {
                return static::bulidFail();
            }

            $this->addAdminLog('修改了' . $model->name);

            return static::bulidSuccess();
        }

        $model->price = $model->price == 0 ? 0 : bcdiv($model->price, '100', 2);
        $model->renew_price = $model->renew_price == 0 ? 0 : bcdiv($model->renew_price, '100', 2);
        //$model->gift_discount = $model->gift_discount == 0 ? 0 : bcdiv($model->gift_discount, '100', 2);
        if ($barrage = json_decode($model->barrage, true)) {
            $model->barrage = $barrage;
        } else {
            $model->barrage = [];
        }

        if ($trumpet = json_decode($model->trumpet, true)) {
            $model->trumpet_id = $trumpet['props_id'];
            $model->trumpet_num = $trumpet['amount'];
        } else {
            $model->trumpet_id = 0;
            $model->trumpet_num = 0;
        }

        return $this->assign([
            'model' => $model,
            'props' => PropsNewModel::listByType(),
            'barrage' => PropsNewModel::listByType(101),
            'trumpet' => PropsNewModel::listByType(100),
        ])->fetch();
    }

    public function level_add()
    {
        if ($this->request->isAjax()) {
            if (!$name = trim($this->post('name', ''))) {
                return static::bulidFail('等级名称不能为空');
            }

            if (!($rank_id = $this->post('rank_id')) || !is_numeric($rank_id)) {
                return static::bulidFail('等级序号错误');
            }

            if (!($price = rtrim(trim($this->post('price', '')), '.')) || !is_numeric($price)) {
                return static::bulidFail('价格不能为空');
            }

            if (!($renew_price = rtrim(trim($this->post('renew_price', '')), '.')) || !is_numeric($renew_price)) {
                return static::bulidFail('续费价格不能为空');
            }

            $weight = trim($this->post('weight', ''));
            if (!is_numeric($weight) || $weight < 0) {
                return static::bulidFail('权重不能为空');
            }

            if (!($promo_id = trim($this->post('promo_id', ''))) || !is_numeric($promo_id)) {
                return static::bulidFail('请选择优惠');
            }

            if (!in_array($promo_id, array_column(NoblePromoModel::lists(), 'id'))) {
                return static::bulidFail('不存在的优惠');
            }

            if (!($gift_id = trim($this->post('gift_id', ''))) || !is_numeric($gift_id)) {
                return static::bulidFail('请选择礼物');
            }

            if (!in_array($gift_id, array_column(GiftModel::lists(), 'id'))) {
                return static::bulidFail('不存在的礼物');
            }

            $is_vip_service = 0;
            $is_prevent_ban = 0;
            $is_vip_seat = 0;

            if (trim($this->post('is_vip_service', ''))) {
                $is_vip_service = 1;
            }

            if (trim($this->post('is_prevent_ban', ''))) {
                $is_prevent_ban = 1;
            }

            if (trim($this->post('is_vip_seat', ''))) {
                $is_vip_seat = 1;
            }

            Db::startTrans();
            try {
                if (!$model = NobleModel::create([
                    'name' => $name,
                    'price' => bcmul($price, '100', 0),
                    'rank_id' => $rank_id,
                    'renew_price' => bcmul($renew_price, '100', 0),
                    'weight' => $weight,
                    'promo_id' => $promo_id,
                    'gift_id' => $gift_id,
                    'is_vip_service' => $is_vip_service,
                    'is_prevent_ban' => $is_prevent_ban,
                    'is_vip_seat' => $is_vip_seat,
                ])) {
                    return static::bulidFail();
                }

                NoblePrivilegeModel::create([
                    'noble_id' => $model->id,
                    'mount_title' => '',
                    'mount_description' => '',
                    'promo_title' => '',
                    'promo_description' => '',
                    'prop_title' => '',
                    'prop_description' => '',
                    'vip_service_title' => '',
                    'vip_service_description' => '',
                    'speak_title' => '',
                    'speak_description' => '',
                    'prevent_ban_title' => '',
                    'prevent_ban_description' => '',
                    'vip_seat_title' => '',
                    'vip_seat_description' => '',
                    'sticker_title' => '',
                    'sticker_description' => '',
                    'gift_title' => '',
                    'gift_description' => '',
                ]);

                Db::commit();;
                return static::bulidSuccess();

            } catch (Exception $exception) {
                Db::rollback();
                return static::bulidFail();
            }
        }
        return $this->assign([
            'gifts' => GiftModel::lists(),
            'noble_promos' => NoblePromoModel::lists()
        ])->fetch();
    }

    public function level_del()
    {
        if (!($id = trim($this->get('id', ''))) || !is_numeric($id)) {
            return static::bulidFail();
        }

        if (!$model = NobleModel::field('id')->where('id', $id)->find()) {
            return static::bulidFail();
        }

        Db::startTrans();
        try {
            if (!$model->delete()) {
                return static::bulidFail();
            }

            if ($model = NoblePrivilegeModel::where('noble_id', $id)->find()) {
                $model->delete();
            }

            Db::commit();
            return static::bulidSuccess();
        } catch (Exception $exception) {
            Db::rollback();
            return static::bulidFail();
        }
    }

    public function copywriting()
    {
        if (!ctype_digit($noble_id = $this->get('noble_id', ''))) {
            return static::bulidFail('贵族ID错误');
        }

        if (!$model = NoblePrivilegeModel::where('noble_id', $noble_id)->find()) {
            return static::bulidFail('该贵族相关文案不存在');
        }

        if ($this->request->isAjax()) {
            $model->mount_title = trim($this->post('mount_title', ''));
            $model->mount_description = trim($this->post('mount_description', ''));
            $model->promo_title = trim($this->post('promo_title', ''));
            $model->promo_description = trim($this->post('promo_description', ''));
            $model->prop_title = trim($this->post('prop_title', ''));
            $model->prop_description = trim($this->post('prop_description', ''));
            $model->vip_service_title = trim($this->post('vip_service_title', ''));
            $model->vip_service_description = trim($this->post('vip_service_description', ''));
            $model->speak_description = trim($this->post('speak_description', ''));
            $model->prevent_ban_title = trim($this->post('prevent_ban_title', ''));
            $model->prevent_ban_description = trim($this->post('prevent_ban_description', ''));
            $model->vip_seat_title = trim($this->post('vip_seat_title', ''));
            $model->vip_seat_description = trim($this->post('vip_seat_description', ''));
            $model->sticker_title = trim($this->post('sticker_title', ''));
            $model->sticker_description = trim($this->post('sticker_description', ''));
            $model->gift_title = trim($this->post('gift_title', ''));
            $model->gift_description = trim($this->post('gift_description', ''));

            if (!$model->save()) {
                return static::bulidFail();
            }

            return static::bulidSuccess();
        }

        return $this->assign(['model' => $model])->fetch();
    }
}
